package org.theconservationagency.utils;

import java.io.IOException;

public class YearExtractor {

	private int earliest = Integer.MAX_VALUE;
	private int latest = Integer.MIN_VALUE;
	
	private static final int NUMBERS_IN_YEAR_STRING = 4;
	
	public YearExtractor(int earlest, int latest) throws IOException {
		this.earliest = earlest;
		this.latest = latest;
		if (earlest>latest) {
			throw new IOException("Configuration error: earlest year("
					+ String.valueOf(this.earliest)
					+ ") should be no greater than latest year("
					+ String.valueOf(this.latest)
					+ ").");
		}
	}
	
	/**
	 * Given a row of string, 
	 * 	1. try to find out any 4 consecutive numbers. return -1 if it cannot find it.
	 *  2. parse number candidate - if it's not in range, return -2.
	 * @param row
	 * @return
	 */
	public int extractYear(String row) {
		
		int accumDigits = 0;
		int candidate;
		
		for (int i=0; i<row.length(); i++) {
			if (Character.isDigit(row.charAt(i))) {
				
				accumDigits++;
				
			} else {
				
				if (accumDigits==NUMBERS_IN_YEAR_STRING) {
					candidate = Integer.parseInt(row.substring(i-NUMBERS_IN_YEAR_STRING, i));
					if (isInGivenYears(candidate)) {
						return candidate;
					}
					
				} 

				accumDigits = 0;
				
			}
		}
		return -1;
		
	}
	
	private boolean isInGivenYears(int year) {
		return year>=earliest && year<=latest;
	}
	
}
